package com.sqk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sqk.reggie.common.BaseContext;
import com.sqk.reggie.common.Result;
import com.sqk.reggie.pojo.AddressBook;
import com.sqk.reggie.pojo.User;
import com.sqk.reggie.service.AddressBookService;
import com.sqk.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 地址簿管理
 */
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    /**
     * 地址列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<AddressBook>> list(){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, BaseContext.getCurrentId());
        User user = userService.getOne(queryWrapper);

        //根据当前用户的ID查询其地址
        LambdaQueryWrapper<AddressBook> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(AddressBook::getUserId,user.getId());
        List<AddressBook> addressBooks = addressBookService.list(queryWrapper1);

        return Result.success(addressBooks);
    }

    /**
     * 添加地址信息
     * @param addressBook
     * @return
     */
    @PostMapping
    public Result<AddressBook> save(@RequestBody AddressBook addressBook){

        //设置UserId
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, BaseContext.getCurrentId());
        User user = userService.getOne(queryWrapper);
        addressBook.setUserId(user.getId());

        addressBookService.save(addressBook);
        return Result.success(addressBook);
    }

    @PutMapping("/default")
    public Result<List<AddressBook>> updateDefault(@RequestBody AddressBook addressBook){
        List<AddressBook> addressBookList = addressBookService.list();
        addressBookList = addressBookList.stream().map(item -> {
            item.setIsDefault(0);
            addressBookService.updateById(item);
            return item;
        }).collect(Collectors.toList());

        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return Result.success(addressBookList);
    }

    /**
     * 获取默认地址
     * @return
     */
    @GetMapping("/default")
    public Result<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        return Result.success(addressBook);
    }

}
